﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Reflection;
using System.Diagnostics;
using System.Threading;
using System.Windows.Threading;
using System.Collections;

namespace AIConvertTool
{

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        /// <summary>
        /// 转化刷新定时器
        /// </summary>
        private DispatcherTimer _convertTimer;

        static string iniPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config.ini");
        IniFiles ini = new IniFiles(iniPath);
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = this;
            getIniFileItems();
            InitializeConvertTimer();
        }

        /// <summary>
        /// 初始转化刷新定时器
        /// </summary>
        private void InitializeConvertTimer()
        {
            _convertTimer = new DispatcherTimer();
            _convertTimer.Interval = TimeSpan.FromMilliseconds(2000);
            _convertTimer.Tick += Convert_Tick;
            _convertTimer.Start();
        }

        private async void Convert_Tick(object sender, EventArgs e)
        {
            if (AutoConvert.IsChecked == true)
            {
                ini.IniWriteValue("History", "AutoConvert", "true");

                if (!IsConvertTaskRunning)
                {
                    ConvertTask();
                }
            }
            else
            {
                ini.IniWriteValue("History", "AutoConvert", "false");
            }
        }

        private void getIniFileItems()
        {
            ini.FindAndCreate(iniPath);
            PromptText.Text = ini.IniReadValue("History", "PromptText");
            SaveFolder.Text = ini.IniReadValue("History", "SaveFolder");
            SourceFolder.Text = ini.IniReadValue("History", "SourceFolder");
            if (ini.IniReadValue("History", "AutoConvert") == "true")
            {
                AutoConvert.IsChecked = true;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                SourceFolder.Text = dialog.SelectedPath;
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                SaveFolder.Text = dialog.SelectedPath;
            }
        }

        private async Task ProcessUncompletedFileAsync(string promptText, string folderAPath, string folderBPath, FileInfoModel fileInfo)
        {
            // 创建 Stopwatch 实例
            Stopwatch stopwatch = new Stopwatch();

            // 开始计时
            stopwatch.Start();
            // Read text from the uncompleted file
            var filePathA = System.IO.Path.Combine(folderAPath, fileInfo.FileName);
            LogText.Text += $"{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}{fileInfo.FileName} 转换中...\r\n";
            LogText.ScrollToEnd();
            var originalText = await File.ReadAllTextAsync(filePathA);

            // Update the file's status to InProgress
            fileInfo.Status = FileStatus.进行中;
            
            AIConvert AIConvertObj = new AIConvert();
            // Simplify the text using AI (replace this with your actual AI processing logic)
            var simplifiedText = await AIConvertObj.SimplifyTextWithAI(promptText, originalText);

            // Save the simplified text to the corresponding file in folder B
            var filePathB = System.IO.Path.Combine(folderBPath, fileInfo.FileName);
            await File.WriteAllTextAsync(filePathB, simplifiedText);

            // Update the file's status to Completed
            fileInfo.Status = FileStatus.已完成;
            // 停止计时
            stopwatch.Stop();

            LogText.Text += $"{DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss")}{fileInfo.FileName} 转换完成！耗时：{stopwatch.Elapsed.TotalSeconds}s\r\n";
            LogText.ScrollToEnd();
        }


        private CancellationTokenSource _cancellationTokenSource;
        public bool IsConvertTaskRunning { get; private set; }

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (!IsConvertTaskRunning)
            {
                ConvertTask();
            } else
            {
                // 处理取消操作
                IsConvertTaskRunning = false;
                ConvertButton.Content = "自动检查并处理";
                ConvertButton.Background = new SolidColorBrush(Colors.LightGray);
            }
        }

        private async void ConvertTask()
        {
            IsConvertTaskRunning = true;
            _cancellationTokenSource = new CancellationTokenSource();
            ConvertButton.Content = "正在检查并转换...";
            ConvertButton.Background = new SolidColorBrush(Colors.Yellow);

            try
            {
                await LongRunningOperationAsync(_cancellationTokenSource.Token);
            }
            catch (OperationCanceledException)
            {
                // 处理取消操作
                IsConvertTaskRunning = false;
                ConvertButton.Content = "自动检查并处理";
                ConvertButton.Background = new SolidColorBrush(Colors.LightGray);
            }
        }

        private async Task LongRunningOperationAsync(CancellationToken cancellationToken)
        {
            // 这里是异步操作的内容
            bool entry = false;
            string aiType = ini.IniReadValue("AISetting", "AI_TYPE");
            switch (aiType)
            {
                case "1":
                    if (ini.IniReadValue("AISetting", "API_KEY") != "" && ini.IniReadValue("AISetting", "API_URL") != "") entry = true;
                    break;
                case "2":
                    if (ini.IniReadValue("AISetting", "YIYAN_API_KEY") != "" && ini.IniReadValue("AISetting", "YIYAN_API_URL") != "") entry = true;
                    break;
                case "3":
                    if (ini.IniReadValue("AISetting", "QWEN_API_KEY") != "" && ini.IniReadValue("AISetting", "QWEN_API_URL") != "") entry = true;
                    break;
                default:
                    break;
            }
            if (entry == true)
            {
                string folderAPath = SourceFolder.Text;
                string folderBPath = SaveFolder.Text;
                string promptText = PromptText.Text;
                ini.IniWriteValue("History", "PromptText", promptText);
                ini.IniWriteValue("History", "SourceFolder", folderAPath);
                ini.IniWriteValue("History", "SaveFolder", folderBPath);

                LoadAndCompareFiles(folderAPath, folderBPath);

                var fileInfos = FilesDataGrid.ItemsSource as List<FileInfoModel>;

                // 创建一个任务列表来存储所有待处理的文件任务
                var processingTasks = new List<Task>();
                int i = 0;

                try
                {
                    var uncompletedFiles = fileInfos.Where(fi => fi.Status == FileStatus.未完成).ToList();

                    foreach (var fileInfo in uncompletedFiles)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        //await ProcessUncompletedFileAsync(promptText, folderAPath, folderBPath, fileInfo);

                        // 创建一个新任务来处理文件，并添加到任务列表中
                        // 注意：这里传递cancellationToken给ProcessUncompletedFileAsync方法
                        var processingTask = ProcessUncompletedFileAsync(promptText, folderAPath, folderBPath, fileInfo)
                            .ContinueWith(t =>
                            {
                                // 处理异常
                                if (t.IsFaulted && t.Exception != null)
                                {
                                }
                            }, cancellationToken);
                        processingTasks.Add(processingTask);
                        i++;
                        int processTaskCount = 1;
                        try
                        {
                            if (int.Parse(ProcessTaskCount.Text) > 1)
                            {
                                processTaskCount = int.Parse(ProcessTaskCount.Text);
                            }
                        } catch { }
                        if (i >= processTaskCount)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex) { }

                // 等待所有处理任务完成
                await Task.WhenAll(processingTasks);
                // MessageBox.Show(i.ToString());

                // 处理取消操作
                IsConvertTaskRunning = false;
                ConvertButton.Content = "自动检查并处理";
                ConvertButton.Background = new SolidColorBrush(Colors.LightGray);
            }
            else
            {
                // 处理取消操作
                IsConvertTaskRunning = false;
                ConvertButton.Content = "自动检查并处理";
                ConvertButton.Background = new SolidColorBrush(Colors.LightGray);
                MessageBox.Show("请先设置AI信息。");
            }
        }

        private void LoadAndCompareFiles(string folderAPath, string folderBPath)
        {
            if (folderAPath != "" && folderBPath != "")
            {
                try
                {
                    var filesInFolderA = Directory.GetFiles(folderAPath, "*.txt", SearchOption.TopDirectoryOnly);
                    var filesInFolderB = Directory.GetFiles(folderBPath, "*.txt", SearchOption.TopDirectoryOnly);
                    var fileDataList = new List<FileInfoModel>();

                    foreach (var filePathA in filesInFolderA)
                    {
                        var fileName = System.IO.Path.GetFileName(filePathA);
                        FileStatus status = filesInFolderB.Contains(System.IO.Path.Combine(folderBPath, fileName)) ? FileStatus.已完成 : FileStatus.未完成;
                        fileDataList.Add(new FileInfoModel { FileName = fileName, Status = status });
                    }
                    FilesDataGrid.ItemsSource = fileDataList;
                } catch (Exception ex)
                {
                    MessageBox.Show("未找到对应路径");
                }
            } else
            {
                MessageBox.Show("请填写路径");
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            AISettingsWindow AISettingsWindow = new AISettingsWindow();
            AISettingsWindow.Owner = this; // 设置主窗口为设置窗口的Owner，以便设置窗口在主窗口之上显示并保持中心对齐
            AISettingsWindow.ShowDialog(); // 显示设置窗口为模态对话框
        }

    }
}
